import requests,time,smtplib,random,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

agents = [
    'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19',
    'Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
    'Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
    'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0',
    'Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0',
    'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36',
    'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19',
    'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
    'Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
]
headers = {
    'User-Agent': agents[random.randint(0, len(agents) - 1)],
}

def getPage():
    count = 1
    while count < 4:
        try:
            url = 'https://api.github.com/search/repositories?q=CVE-2020&sort=updated'
            response = requests.get(url=url, headers=headers, timeout=5)
            if response.status_code == 200:
                total_count = response.json().get('total_count')
                num = total_count % 30
                if num == 0:
                    page_num = total_count // 30
                else:
                    page_num = total_count // 30 + 1
                return page_num
            else:
                print("Github连接失败，第{}次请求重试".format(count))
        except:
            pass
        count += 1
        time.sleep(5)
    else:
        print("Github连接失败，请稍后重试")
        return False

def getNews():
    page_nums = getPage()
    if page_nums is False:
        pass
    else:
        for page_num in range(1,page_nums+1):
            count = 1
            while count < 4:
                try:
                    url = 'https://api.github.com/search/repositories?q=CVE-2020&sort=updated&page={}'.format(page_num)
                    response = requests.get(url=url,headers=headers,timeout=5)
                    if response.status_code == 200:
                        writeNews(response)
                        break
                    else:
                        print("Github连接失败，第{}次请求重试".format(count))
                        time.sleep(5)
                except:
                    pass
                count += 1
            else:
                print("Github连接失败，请稍后重试")
            time.sleep(10)

def writeNews(response):
    items = response.json().get('items')
    if not os.path.exists("CVE-2020"):
        os.makedirs("CVE-2020")
    for item in items:
        id = item.get('id')
        cve_name = item.get('name')
        html_url = item.get('html_url')
        description = item.get('description')
        file = open('CVE-2020\\{}.txt'.format(time.strftime('%Y-%m-%d %X',time.localtime()).split()[0]),'a+',encoding='utf-8')
        if not os.path.exists("CVE-2020\{}.txt".format(cve_name)):
            f = open('CVE-2020\\{}.txt'.format(cve_name), 'w',encoding='utf-8')
            print("用户id:{}\n项目名：{}\n项目链接：{}\n描述:{}".format(id,cve_name,html_url,description))
            f.write("用户id:{}\n项目名：{}\n项目链接：{}\n描述:{}\n".format(id,cve_name,html_url,description))
            file.write("用户id:{}\n项目名：{}\n项目链接：{}\n描述:{}\n".format(id,cve_name,html_url,description))
            f.close()
        file.close()

def sendMail():
    my_sender = 'xxx@qq.com'  #发送邮箱
    my_pass = 'xxxxx'         #邮箱授权密码
    my_user = 'xxx2@qq.com'   #接收邮箱
    try:
        msg = MIMEMultipart()
        msg['From'] = Header("发送人", 'utf-8')
        msg['To'] = Header("收件人", 'utf-8')
        subject = 'Github又更新新项目了'
        msg['Subject'] = Header(subject, 'utf-8')
        file_path_name = 'CVE-2020\\{}.txt'.format(time.strftime('%Y-%m-%d %X',time.localtime()).split()[0])
        file_name = file_path_name.split('\\')[1]
        msg.attach(MIMEText('Github又更新新项目了', 'plain', 'utf-8'))
        att = MIMEText(open(file_path_name, 'rb').read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename={}'.format(file_name)
        msg.attach(att)
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, my_user, msg.as_string())
        print("Successful: 邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

def main():
    getNews()
    sendMail()

if __name__ == '__main__':
    while True:
        main()
        #等待一天
        time.sleep(43200)
